const Router = require('koa-router');
const {db, Op,QueryTypes } = require("../../models/db");
const { xe} = require("../../tools/tool");
const router = new Router();

// 退货订单
router.post('/zd/backList', async ctx => {
    let usr = ctx.user
    let tenantId = usr.tenantId;
    let buId = usr.buId;
    let searchTxt = ctx.request.body.searchTxt?xe.trim(ctx.request.body.searchTxt):'';
    let currentPage = ctx.request.body.currentPage?ctx.request.body.currentPage:1;
    let pageSize = 20;
    let skip = (currentPage - 1) * pageSize;
    let sql = `select tenantId,id,buId,billState,billDate,billNo,amount from invoice 
        where tenantId=${tenantId} and billState='accounted' and buId=${buId}   and transType=150602 
        and (goods like '%${searchTxt}%' or '${searchTxt}'='')
        order by billDate desc offset ${skip} rows fetch next ${pageSize} rows only;
    `
    let list = await db.query(sql, {type: QueryTypes.SELECT})
    let ids = []
    if(list.length > 0) {
        list.map(row => {
            ids.push(row.id)
        })
        let detail = await db.query(`select * from v_main_info where tenantId=${tenantId} and iid in(${ids.join(',')})`, {type: QueryTypes.SELECT})
        detail.map(row => {
            row.deduction = xe.toNumber(row.deduction)
            row.amount = xe.toNumber(row.amount)
            row.price = xe.toNumber(row.price)
        })
        let gp = xe.groupBy(detail, 'iid')
        list.map(row => {
            row.amount = xe.toFixed(row.amount, 2)
            row.goods = gp[row.id]
        })
    }
    return ctx.suc('', {list})

})

module.exports = router;
